package net.wlm.others;

import com.alibaba.fastjson.JSON;
import net.wlm.utils.JdbcUtil;
import net.wlm.utils.KafkaUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class JourneyRealtimeAnalyseJob {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 从Kafka消费数据
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "Realtime-vehicle-data");

        // 简化的处理流水线
        DataStream<TripDetectionResult> tripStream = kafkaStream
                .map(value -> {
                    try {
                       // System.out.println("Processing: " + value); // 调试输出
                        return JSON.parseObject(value, CarBean.class);
                    } catch (Exception e) {
                       // System.err.println("JSON parse error: " + value);
                        return null;
                    }
                })
                .filter(bean -> bean != null)
                .keyBy(CarBean::getVin)
                .process(new JourneyRealtimeFunction())
                .name("simplified-trip-detector");
        // 输出结果
        SingleOutputStreamOperator<String> map = tripStream.map(new MapFunction<TripDetectionResult, String>() {
            @Override
            public String map(TripDetectionResult value) throws Exception {
                String output = value.getVin() + ',' +
                        value.getTripId() + ',' +
                        value.getStartTime() + ',' +
                        value.getEndTime() + ',' +
                        value.getDistance() ;
                //System.out.println(output);
                return output;
            }

        });

         // 插入数据
        String upsertSql = "INSERT INTO table vehicle_real.car_realtime (Vin, tripId, startTime, endTime,distance)\n" +
                "VALUES (?, ?, ?, ?,?)";
        //  插入数据
        JdbcUtil.sinkToClickhouseUpsert( map, upsertSql);

        env.execute("JourneyRealtimeAnalyseJob");
    }
}